import {Table} from "antd";
import _ from "lodash";
import {useEffect, useState} from "react";

const getVal = val => {
    if (_.isNumber(val) && !_.isInteger(val)) {
        return Number(val).toFixed(2);
    }
    return val;
};

const filterData = data => {
    const keys = Object.keys(data[0]);
    const res: any[] = _.map(keys, item => {
        const title = item.includes("EMPTY") ? "" : item.split("_")[0];
        return {
            title,
            dataIndex: item,
            key: item,
            align: "center",
            render: val => {
                if (_.isArray(val)) {
                    return (
                        <div>
                            {_.map(val, item => {
                                const num = getVal(item);
                                return (
                                    <div key={item} style={{color: "#333", paddingBottom: 10}}>
                                        {num}
                                    </div>
                                );
                            })}
                        </div>
                    );
                }
                return getVal(val);
            },
        };
    });
    return res;
};

const BaseTable = ({name}) => {
    const [columns, setColumns] = useState([]);
    const [data, setData] = useState([]);

    const handleInit = () => {
        const filePath = `/json/${name}.json`;
        fetch(filePath)
            .then(response => response.json())
            .then(data => {
                const res = filterData(data);
                setColumns(res);
                setData(data);
            })
            .catch(error => {
                console.error("发生错误:", error);
            });
    };

    useEffect(() => {
        handleInit();
    }, [name]);
    return (
        <Table
            style={{marginTop: 20}}
            dataSource={data}
            bordered
            pagination={false}
            scroll={{x: "auto"}}
            rowKey={row => JSON.stringify(row)}
            columns={columns}
        />
    );
};

export default BaseTable;
